﻿using Dapper;
using DapperWrapper;
using System;
using System.Collections.Generic;
using System.Text;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.DapperWrapper.SqlServer;
using ZLWeb.WebApiEntityBase;
using ZLWeb.WebApiRepository.Base;

namespace ZilLion.Service.Core.CommonRepository
{
    public class CRMSqlServerRespository<T> : SqlServerRespository<T> where T : class
    {
        public CRMSqlServerRespository():base(new SourceAContext())
        {
        }
        public CRMSqlServerRespository(IDbContext DbContext) : base(DbContext)
        {
        }

        protected long Accid { get; set; }

        protected ErrorModel error = new ErrorModel();

        public CRMSqlServerRespository(long? Accid)
        {
            if (Accid == null)
            {
                Context = new SourceContext();
            }
            else
            {
                SqlConnectionLoader accidloader = new SqlConnectionLoader(Accid.GetValueOrDefault());
                SetDbContext(accidloader.GetDbContext());
            }
            this.Accid = Accid.GetValueOrDefault();
        }

        protected t ReturnResponseResultInfo<t>(DynamicParameters p) where t : ResponseResultInfo, new()
        {
            var preturn = p.Get<int>("return");
            if (preturn == 1)
            {
                return new t() { Errormodel = HasErrormodel(error) ? error : new ErrorModel() };
            }
            return null;
        }

        private bool HasErrormodel(ErrorModel errormodel)
        {
            if (errormodel == null)
            {
                return false;
            }
            if (string.IsNullOrEmpty(errormodel.Errtype))
            {
                return false;
            }
            return true;
        }
    }
}
